import CoreBluetooth
import DCloudUTSFoundation

public class BluetoothAdapterManager: NSObject {
    // 蓝牙适配器管理对象
    private var centralManager: CBCentralManager?
    private var peripheralManager: CBPeripheralManager?
	private var allowedUUIDs: [String] = [] // 存储需要处理的设备 UUID 字符串
	private var lastReportTime: [String: Date] = [:] // 存储每个设备上次上报的时间
	private var reportInterval: TimeInterval = 0 // 设置上报时间间隔，单位为秒
    // 获取已发现的蓝牙设备
    private var discoveredPeripherals = [CBPeripheral]()
    private var deviceList = [BluetoothDevice]()
	private var allowDuplicatesKey: Bool = false // 是否允许重复上报同一设备
	private var discoveredPeripheralsRSSI: [String: NSNumber] = [:]
    // 蓝牙适配器状态变化回调
    private var onBluetoothAdapterStateChangeCallback: ((BluetoothAdapterState) -> Void)?
    // 发现新设备监听回调
    private var onDeviceFoundCallback: ((BluetoothDevice) -> Void)?
    // 蓝牙低功耗连接状态变化监听回调
    private var onBLEConnectionStateChangeCallback: ((BLEConnectionState) -> Void)?
    // 读取特征值监听回调
    private var onCharacteristicValueChangeCallback: ((CharacteristicValueChange) -> Void)?
    private var bluetoothAvailable: Bool = false
    private var connectTimeoutTimer: DispatchSourceTimer?
    private var scanning: Bool = false
    // 尝试连接的设备ID
    private var deviceIdToConnect: String?
    // 用于存储每个设备的服务集合
    private var deviceServices: [String: [BluetoothDeviceService]] = [:]
    // 用于存储每个服务的特征集合
    private var serviceCharacteristics: [String: [BluetoothDeviceCharacteristic]] = [:]
    // 用于存储已经连接的设备
    private var connectedPeripherals: Set<String> = Set()
    // 用于存储当前获得的服务特征
    private var currentCharacteristics: [CharacteristicKey: CBCharacteristic] = [:]
    // 用于存储特征 ID 到服务 ID 的映射
    private var characteristicToServiceMap: [String: String] = [:]

    // 连接状态的变化
    public enum BluetoothConnectionStatus {
        case connected
        case disconnected
        case failed
        case lost
    }

    // 蓝牙主机/从机模式
    public enum BluetoothMode {
        case central
        case peripheral
    }

    public init(mode: BluetoothMode = .central) {
        super.init()
        switch mode {
        case .central:
            centralManager = CBCentralManager(delegate: self, queue: nil)
        case .peripheral:
            peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        }
    }

    // 监听蓝牙适配器状态变化
    public func onBluetoothAdapterStateChange(_ callback: @escaping (BluetoothAdapterState) -> Void) {
        onBluetoothAdapterStateChangeCallback = callback
    }

    // 监听蓝牙低功耗连接状态变化
    public func onBLEConnectionStateChange(_ callback: @escaping (BLEConnectionState) -> Void) {
        onBLEConnectionStateChangeCallback = callback
    }

    // 监听发现的新设备
    public func onDeviceFound(_ callback: @escaping (BluetoothDevice) -> Void) {
        onDeviceFoundCallback = callback
    }

    // 服务特征值变化
    public func onBLECharacteristicValueChange(_ callback: @escaping (CharacteristicValueChange) -> Void) {
        onCharacteristicValueChangeCallback = callback
    }

    // 检查设备是否已被发现
    public func isDeviceDiscovered(deviceId: String) -> Bool {
        return discoveredPeripherals.contains(where: { $0.identifier.uuidString == deviceId })
    }

    // 检查设备是否可以连接
    public func canDeviceConnected(deviceId: String) -> Bool {
        // 通过设备的 BluetoothDevice 来检查是否可连接
        guard let bluetoothDevice = deviceList.first(where: { $0.deviceId == deviceId }) else {
            return false
        }

        // 检查设备是否可连接
        if !bluetoothDevice.connectable {
            return false
        }

        return true
    }

    // 检查设备是否已经连接
    public func isDeviceConnected(deviceId: String) -> Bool {
        return connectedPeripherals.contains(deviceId)
    }

    // 检查服务是否存在
    public func isServiceExist(deviceId: String, serviceId: String) -> Bool {
        guard let services = deviceServices[deviceId] else {
            return false
        }

        return services.contains { $0.uuid == serviceId }
    }

    // 根据设备ID、服务ID和特征ID获取特征
    public func getCharacteristic(deviceId: String, serviceId: String, characteristicId: String) -> CBCharacteristic? {
        let key = CharacteristicKey(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId)
        return currentCharacteristics[key]
    }

    // 检查服务特征是否存在
    public func isCharacteristicExist(deviceId: String, serviceId: String, characteristicId: String) -> Bool {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            return false
        }
        return true
    }

    // 检查特征是否支持 notify 或者 indicate
    public func isCharacterContainsNotify(deviceId: String, serviceId: String, characteristicId: String) -> Bool {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            return false
        }
        return characteristic.properties.contains(.notify) || characteristic.properties.contains(.indicate)
    }

    // 检查特征是否支持 read
    public func isCharacterContainsRead(deviceId: String, serviceId: String, characteristicId: String) -> Bool {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            return false
        }
        return characteristic.properties.contains(.read)
    }

    // 检查特征是否支持 write
    public func isCharacterContainsWrite(deviceId: String, serviceId: String, characteristicId: String) -> Bool {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            return false
        }
        return characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse)
    }

    public func setCharacterNotify(deviceId: String, serviceId: String, characteristicId: String) {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            return
        }
        // 确保 peripheral 是 CBPeripheral 类型
        guard let peripheral = discoveredPeripherals.first(where: { $0.identifier.uuidString == deviceId }) else {
            return
        }
        if (isCharacterContainsNotify(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId)) {
            peripheral.setNotifyValue(true, for: characteristic)
        }
    }

    // 读取特征值
    func readCharacteristicValue(deviceId: String, serviceId: String, characteristicId: String) {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            // console.log("未找到特征：\(characteristicId)")
            return
        }
        // 查找设备
        guard let peripheral = discoveredPeripherals.first(where: { $0.identifier.uuidString == deviceId }) else {
            // console.log("未找到设备：\(deviceId)")
            return
        }
        characteristicToServiceMap[characteristicId] = serviceId
        // 读取特征值
        peripheral.readValue(for: characteristic)
    }

    // 写入特征值
    func writeBLECharacteristicValue(deviceId: String, serviceId: String, characteristicId: String, value: [UInt8]) {
        // 查找特征
        guard let characteristic = getCharacteristic(deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId) else {
            // console.log("未找到特征：\(characteristicId)")
            return
        }
         // 查找设备
        guard let peripheral = discoveredPeripherals.first(where: { $0.identifier.uuidString == deviceId }) else {
            // console.log("未找到设备：\(deviceId)")
            return
        }
        // 检查特征是否支持写入
        if characteristic.properties.contains(.write) {
            // 将字节数组转换为 Data 对象
            let data = Data(value)

            // 使用 withResponse 类型写入数据
            peripheral.writeValue(data, for: characteristic, type: .withResponse)
        } else if characteristic.properties.contains(.writeWithoutResponse) {
            // 将字节数组转换为 Data 对象
            let data = Data(value)

            // 使用 withoutResponse 类型写入数据
            peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
        } else {
            // console.log("特征不支持写入：\(characteristicId)")
        }
    }

    // 开始扫描蓝牙设备
    func startBluetoothDevicesDiscovery(services: [String]?, forAllowDuplicatesKey: Bool?, forInterval: Double?) {
        guard let centralManager = centralManager else { return }
		if let uuids = services {
			allowedUUIDs = uuids
		}
		if let toAllowDuplicatesKey = forAllowDuplicatesKey {
			allowDuplicatesKey = toAllowDuplicatesKey
		}
		if let toInterval = forInterval {
			reportInterval = toInterval
		}
        scanning = true
        centralManager.scanForPeripherals(withServices: nil, options: nil)
        onBluetoothAdapterStateChangeCallback?(BluetoothAdapterState(
            discovering: scanning,
            available: bluetoothAvailable
        ))
    }

    // 停止扫描蓝牙设备
    func stopBluetoothDevicesDiscovery() {
        guard let centralManager = centralManager else { return }
        scanning = false
        centralManager.stopScan()
        onBluetoothAdapterStateChangeCallback?(BluetoothAdapterState(
            discovering: scanning,
            available: bluetoothAvailable
        ))
    }

    // 连接蓝牙设备
    func createBLEConnection(to deviceId: String, timeout: Int?) {
        deviceIdToConnect = deviceId
        // 查找设备
        guard let peripheral = discoveredPeripherals.first(where: { $0.identifier.uuidString == deviceId }) else {
            // console.log("未找到设备：\(deviceId)")
            onBLEConnectionStateChangeCallback?(BLEConnectionState(
                deviceId: deviceId,
                connected: false,
                connectionFailStatus: 1
            ))
            return
        }

        // 通过设备的 BluetoothDevice 来检查是否可连接
        guard let bluetoothDevice = deviceList.first(where: { $0.deviceId == deviceId }), bluetoothDevice.connectable else {
            // console.log("设备不可连接：\(deviceId)")
            onBLEConnectionStateChangeCallback?(BLEConnectionState(
                deviceId: deviceId,
                connected: false,
                connectionFailStatus: 2 // 设备不可连接
            ))
            return
        }

        // 设置连接超时
        if let timeout = timeout {
            setConnectionTimeout(timeout)
        }

        // 连接蓝牙设备
        guard let centralManager = centralManager else { return }
        centralManager.connect(peripheral, options: nil)
    }

    // 设置连接超时
    private func setConnectionTimeout(_ timeout: Int) {
        // 如果有超时定时器，则取消
        if let timer = connectTimeoutTimer {
            timer.cancel()
        }

        // 创建新的定时器
        connectTimeoutTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        connectTimeoutTimer?.setEventHandler { [weak self] in
            guard let self = self else { return }

            // 超时操作
            // console.log("蓝牙连接超时")

            // 获取当前正在连接的外设
            if let peripheral = self.discoveredPeripherals.first(where: { $0.identifier.uuidString == self.deviceIdToConnect }) {
                // 断开连接
                self.centralManager?.cancelPeripheralConnection(peripheral)

                // 触发连接失败回调，设置连接失败的状态
                self.onBLEConnectionStateChangeCallback?(BLEConnectionState(
                    deviceId: peripheral.identifier.uuidString,
                    connected: false,
                    connectionFailStatus: 5  // 连接超时状态
                ))
            }

            // 取消定时器
            self.connectTimeoutTimer?.cancel()
            self.connectTimeoutTimer = nil
        }

        // 设置定时器的时间（单位：秒）
        connectTimeoutTimer?.schedule(deadline: .now() + .seconds(timeout))
        connectTimeoutTimer?.resume()
    }

    // 连接成功的回调
    private func didConnectDevice(peripheral: CBPeripheral) {
        // 取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // console.log("设备连接成功：\(peripheral.name ?? "Unknown")")
        // 在这里可以进行设备连接成功后的其他操作
    }

    // 连接失败的回调
    private func didFailToConnectDevice(peripheral: CBPeripheral, error: Error?) {
        // 取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // console.log("设备连接失败：\(peripheral.name ?? "Unknown")，错误：\(error?.localizedDescription ?? "无错误描述")")
        // 在这里可以进行连接失败后的其他处理
    }

    // 设备断开连接的回调
    private func didDisconnectDevice(peripheral: CBPeripheral, error: Error?) {
        // 取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // console.log("设备断开连接：\(peripheral.name ?? "Unknown")，错误：\(error?.localizedDescription ?? "无错误描述")")
        // 在这里可以进行设备断开连接后的其他处理
    }

    // 断开蓝牙设备
    func closeBLEConnection(from deviceId: String) -> Bool {
        // 查找设备
        guard let peripheral = discoveredPeripherals.first(where: { $0.identifier.uuidString == deviceId }) else {
            // console.log("未找到设备：\(deviceId)")
            return false
        }

        // 断开连接
        guard let centralManager = centralManager else { return false }
        centralManager.cancelPeripheralConnection(peripheral)
        return true
    }

    // 获取已发现的蓝牙设备列表
    func getDiscoveredPeripherals() -> [CBPeripheral] {
        return discoveredPeripherals
    }

    // 获取蓝牙适配器是否可用
    public func isBluetoothAvailable() -> Bool {
        // console.log("蓝牙可用性：\(bluetoothAvailable ? "是" : "否")")
        return bluetoothAvailable
    }

    // 获取设备服务列表
    public func getBLEDeviceServices(for deviceId: String) -> [BluetoothDeviceService]? {
        return deviceServices[deviceId]
    }

    // 获取服务特征列表
    public func getBLEDeviceCharacteristics(for serviceId: String) -> [BluetoothDeviceCharacteristic]? {
        return serviceCharacteristics[serviceId]
    }

    // 关闭蓝牙适配器
    public func closeBluetoothAdapter() {
        // 停止扫描
        stopBluetoothDevicesDiscovery()

        // 断开所有连接
        guard let centralManager = centralManager else { return }
        for peripheral in discoveredPeripherals {
            centralManager.cancelPeripheralConnection(peripheral)
        }

        // 清空已发现的设备列表
        discoveredPeripherals.removeAll()
        deviceList.removeAll()
        deviceServices.removeAll()
        connectedPeripherals.removeAll()

        // 取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // 释放资源
        centralManager.delegate = nil
        self.centralManager = nil
    }
}

public struct BluetoothDevice {
    var deviceId: String
    var name: String
    var localName: String
    var RSSI: Int
    var advertisementData: [UInt8]
    var advertisementServiceUUIDs: [String]
    var serviceData: [String: Any]
    var connectable: Bool
}

public struct BluetoothAdapterState {
    var discovering: Bool
    var available: Bool
}

public struct BLEConnectionState {
    var deviceId: String
    var connected: Bool
    // 连接失败状态 1.没有找到指定设备 2.连接失败 3.断开连接 4.蓝牙适配器不可用 5.连接超时
    var connectionFailStatus: NSNumber?
}

public struct BluetoothDeviceService {
    var uuid: String
    var isPrimary: Bool
}

public struct BluetoothServiceCharacteristicProperties {
    var read: Bool
    var write: Bool
    var notify: Bool
    var indicate: Bool
    var writeNoResponse: Bool
    var writeDefault: Bool
}

public struct BluetoothDeviceCharacteristic {
    var uuid: String
    var properties: BluetoothServiceCharacteristicProperties
}

public struct CharacteristicKey: Hashable {
    var deviceId: String
    var serviceId: String
    var characteristicId: String
}

public struct CharacteristicValueChange {
    var deviceId: String
    var serviceId: String
    var characteristicId: String
    var value: Data
}

extension BluetoothAdapterManager: CBCentralManagerDelegate {
    /**
     * 蓝牙状态更新时调用
     */
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            // console.log("蓝牙设备已打开")
            bluetoothAvailable = true
            // 开始扫描蓝牙设备等操作
        case .poweredOff:
            // console.log("蓝牙设备已关闭")
            bluetoothAvailable = false
        case .resetting:
            // console.log("蓝牙设备正在重置")
            bluetoothAvailable = false
        case .unauthorized:
            // console.log("蓝牙设备未得到授权")
            bluetoothAvailable = false
        case .unknown:
            // console.log("未知的蓝牙设备状态")
            bluetoothAvailable = false
        case .unsupported:
            // console.log("该设备不支持蓝牙")
            bluetoothAvailable = false
        @unknown default:
            bluetoothAvailable = false
            // console.log("A previously unknown central manager state occurred.")
        }

        onBluetoothAdapterStateChangeCallback?(BluetoothAdapterState(
            discovering: scanning,
            available: bluetoothAvailable
        ))
    }

    // 设备被扫描到的回调
    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
		let peripheralUUIDString = peripheral.identifier.uuidString
		if allowedUUIDs.isEmpty || allowedUUIDs.contains(peripheralUUIDString) {
			// 获取 ManufacturerData
			if let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
			    // 将 Data 转换为 ArrayBuffer 或其他需要的格式
			    let arrayBuffer = convertDataToArrayBuffer(data: manufacturerData)
			    // 直接将 advertisementData 赋值为字节数组
			    var updatedAdvertisementData: [UInt8] = arrayBuffer
			
			    let serviceUUIDStrings = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] ?? []
			    let serviceUUIDStringArray = serviceUUIDStrings.map { $0.uuidString }
			
			    // 获取服务数据（ServiceData），转换为普通对象
			    let serviceData = advertisementData[CBAdvertisementDataServiceDataKey] as? [CBUUID: Data] ?? [:]
			    let convertedServiceData = convertServiceDataToObject(serviceData: serviceData)
			
			    // 构建 BluetoothDevice 对象
			    let device = BluetoothDevice(
			        deviceId: peripheral.identifier.uuidString,
			        name: peripheral.name ?? "Unknown",
			        localName: advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? "Unknown",
			        RSSI: RSSI.intValue,
			        advertisementData: updatedAdvertisementData,
			        advertisementServiceUUIDs: serviceUUIDStringArray,
			        serviceData: convertedServiceData,
			        connectable: advertisementData[CBAdvertisementDataIsConnectable] as? Bool ?? false
			    )
				// 判断是否允许上报同一设备
				if allowDuplicatesKey {
					// 检查 RSSI 值是否不同
					if let recordedRSSI = discoveredPeripheralsRSSI[peripheralUUIDString], recordedRSSI == RSSI {
						return
					}
				} else {
					// 不允许重复上报
					if discoveredPeripherals.contains(peripheral) {
						return
					}
				}
				
				// 未达到上报时间间隔
				if let lastReport = lastReportTime[peripheralUUIDString], Date().timeIntervalSince(lastReport) < reportInterval {
					return
				}
				
				discoveredPeripheralsRSSI[peripheralUUIDString] = RSSI
				lastReportTime[peripheralUUIDString] = Date()
				discoveredPeripherals.append(peripheral)
				deviceList.append(device)
				// 调用回调函数
				onDeviceFoundCallback?(device)
			}
		}
    }

    // 设备连接成功的回调
    public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 设备连接成功取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // 设置外设代理
        peripheral.delegate = self
        // 发现外设上的服务
        peripheral.discoverServices(nil)

        // 更新已连接设备列表
        connectedPeripherals.insert(peripheral.identifier.uuidString)

        onBLEConnectionStateChangeCallback?(BLEConnectionState(
            deviceId: peripheral.identifier.uuidString,
            connected: true
        ))
        // console.log("设备连接成功回调：\(peripheral.name ?? "Unknown")")
    }

    // 设备连接失败的回调
    public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        // 设备连接失败取消超时定时器
        connectTimeoutTimer?.cancel()
        connectTimeoutTimer = nil

        // 更新已连接设备列表
        connectedPeripherals.remove(peripheral.identifier.uuidString)

        onBLEConnectionStateChangeCallback?(BLEConnectionState(
            deviceId: peripheral.identifier.uuidString,
            connected: false,
            connectionFailStatus: 2
        ))
        if let error = error {
            // console.log("设备连接失败：\(peripheral.name ?? "Unknown") 错误：\(error.localizedDescription)")
        } else {
            // console.log("设备连接失败：\(peripheral.name ?? "Unknown")")
        }
    }

    // 设备断开连接的回调
    public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        // 更新已连接设备列表
        connectedPeripherals.remove(peripheral.identifier.uuidString)

        onBLEConnectionStateChangeCallback?(BLEConnectionState(
            deviceId: peripheral.identifier.uuidString,
            connected: false,
            connectionFailStatus: 3
        ))
        // console.log("设备断开连接：\(peripheral.name ?? "Unknown")，错误：\(error?.localizedDescription ?? "无错误描述")")
    }

    private func convertDataToArrayBuffer(data: Data) -> [UInt8] {
        return [UInt8](data)
    }

    private func convertServiceDataToObject(serviceData: [CBUUID: Data]) -> [String: Any] {
        var convertedData: [String: Any] = [:]

        for (key, value) in serviceData {
            let uuidString = key.uuidString  // 将 CBUUID 转换为字符串
            let byteArray = [UInt8](value)  // 将 Data 转换为字节数组
            convertedData[uuidString] = byteArray  // 赋值为普通字典
        }

        return convertedData
    }
}

// 这里是处理服务，发现特征的扩展工具函数
extension BluetoothAdapterManager: CBPeripheralDelegate {
    /**
     * 这里添加CBPeripheralDelegate的方法实现，例如处理服务、发现特征等等
     */
    public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil else {
            // console.log("发现服务时出错：\(error!.localizedDescription)")
            return
        }

        let deviceId = peripheral.identifier.uuidString
        var services = deviceServices[deviceId] ?? []

        peripheral.services?.forEach { service in
            // console.log("发现服务：UUID = \(service.uuid.uuidString), isPrimary = \(service.isPrimary)")
            let newService = BluetoothDeviceService(
                uuid: service.uuid.uuidString,
                isPrimary: service.isPrimary
            )

            services.append(newService)
            peripheral.discoverCharacteristics(nil, for: service)
        }

        deviceServices[deviceId] = services
    }

    public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard error == nil else {
            // console.log("发现特征时出错：\(error!.localizedDescription)")
            return
        }

        let deviceId = peripheral.identifier.uuidString
        let serviceUUID = service.uuid.uuidString
        var characteristics = serviceCharacteristics[serviceUUID] ?? []

        service.characteristics?.forEach { characteristic in
            // console.log("发现特征：\(characteristic.uuid.uuidString)")
            let characteristicId = characteristic.uuid.uuidString
            let key = CharacteristicKey(deviceId: deviceId, serviceId: serviceUUID, characteristicId: characteristicId)
            currentCharacteristics[key] = characteristic

            // 检查特征权限
            let properties = BluetoothServiceCharacteristicProperties(
                read: characteristic.properties.contains(.read),
                write: characteristic.properties.contains(.write),
                notify: characteristic.properties.contains(.notify),
                indicate: characteristic.properties.contains(.indicate),
                writeNoResponse: characteristic.properties.contains(.writeWithoutResponse),
                writeDefault: characteristic.properties.contains(.write)
            )
            // 创建一个新的 BluetoothDeviceCharacteristic 对象
            let newCharacteristic = BluetoothDeviceCharacteristic(
                uuid: characteristic.uuid.uuidString,
                properties: properties
            )
            characteristics.append(newCharacteristic)
        }
        serviceCharacteristics[serviceUUID] = characteristics
    }

    public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            // console.log("读取特征值时出错：\(error!.localizedDescription)")
            return
        }

        if let value = characteristic.value {
            // console.log("读取到特征值：\(characteristic.uuid.uuidString), 值：\(value)")
            // 将 Data 转换为 ArrayBuffer
            let arrayBuffer = value.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> [UInt8] in
                return [UInt8](pointer)
            }
            // 获取服务 ID
            if let serviceId = characteristicToServiceMap[characteristic.uuid.uuidString] {
                // console.log("特征 \(characteristic.uuid.uuidString) 所属的服务 ID 是：\(serviceId)")
                let characteristicValueChange = CharacteristicValueChange(
                    deviceId: peripheral.identifier.uuidString,
                    serviceId: serviceId,
                    characteristicId: characteristic.uuid.uuidString,
                    value: value
                )
                onCharacteristicValueChangeCallback?(characteristicValueChange)
            }
        }
    }

    public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            // console.log("写入特征值时出错：\(error!.localizedDescription)")
            return
        }

        // console.log("写入特征值成功：\(characteristic.uuid.uuidString)")

        // 获取服务 ID
        if let serviceId = characteristicToServiceMap[characteristic.uuid.uuidString] {
            // console.log("特征 \(characteristic.uuid.uuidString) 所属的服务 ID 是：\(serviceId)")

            // 创建 CharacteristicValueChange 对象
            let characteristicValueChange = CharacteristicValueChange(
                deviceId: peripheral.identifier.uuidString,
                serviceId: serviceId,
                characteristicId: characteristic.uuid.uuidString,
                value: characteristic.value ?? Data()
            )

            // 调用回调函数，传递特征值的二进制数据
            onCharacteristicValueChangeCallback?(characteristicValueChange)
        }
    }

    public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            // console.log("更新通知状态时出错：\(error!.localizedDescription)")
            return
        }

        if characteristic.isNotifying {
            // console.log("通知已启用：\(characteristic.uuid.uuidString)")
        } else {
            // console.log("通知已禁用：\(characteristic.uuid.uuidString)")
        }
    }
}

/**
 * 外围设备实现
 */
extension BluetoothAdapterManager: CBPeripheralManagerDelegate {
    // 外围设备管理器状态更新时调用
    public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        switch peripheral.state {
        case .poweredOn:
            console.log("外围设备已打开")
            bluetoothAvailable = true
            // 添加服务和特征
            startAdvertising()
        case .poweredOff:
            console.log("外围设备已关闭")
            bluetoothAvailable = false
        case .resetting:
            console.log("外围设备正在重置")
            bluetoothAvailable = false
        case .unauthorized:
            console.log("外围设备未授权")
            bluetoothAvailable = false
        case .unknown:
            console.log("未知的外围设备状态")
            bluetoothAvailable = false
        case .unsupported:
            console.log("设备不支持外围设备")
            bluetoothAvailable = false
        @unknown default:
            bluetoothAvailable = false
            console.log("A previously unknown peripheral manager state occurred.")
        }

        onBluetoothAdapterStateChangeCallback?(BluetoothAdapterState(
            discovering: scanning,
            available: bluetoothAvailable
        ))
    }

    // 添加服务后调用
    public func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        if let error = error {
            console.log("添加服务失败：\(error.localizedDescription)")
            return
        }
        console.log("服务添加成功：\(service.uuid)")
        // 添加特征
        addCharacteristics(to: service as! CBMutableService)
    }

    // 开始广播服务
    private func startAdvertising() {
        guard let peripheralManager = peripheralManager else { return }
        // 创建并添加服务和特征
        let serviceUUID = CBUUID(string: "your-service-uuid")
        let service = CBMutableService(type: serviceUUID, primary: true)
        peripheralManager.add(service)
        // 开始广播
        peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [serviceUUID], CBAdvertisementDataLocalNameKey: "YourDeviceName"])
    }

    // 添加特征到服务
    private func addCharacteristics(to service: CBMutableService) {
        let characteristicUUID = CBUUID(string: "your-characteristic-uuid")
        let properties: CBCharacteristicProperties = [.read, .write, .notify]
        let characteristic = CBMutableCharacteristic(type: characteristicUUID, properties: properties, value: nil, permissions: .readable)
        service.characteristics = [characteristic]
    }

    // 订阅特征值变化
    public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        console.log("中心设备订阅特征：\(characteristic.uuid)")
    }

    // 取消订阅特征值变化
    public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        console.log("中心设备取消订阅特征：\(characteristic.uuid)")
    }

    // 读取特征值请求
    public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        if request.characteristic.properties.contains(.read) {
            // 处理读取请求
            request.value = getCharacteristicValue(for: request.characteristic)
            peripheral.respond(to: request, withResult: .success)
        } else {
            peripheral.respond(to: request, withResult: .attributeNotFound)
        }
    }

    // 写入特征值请求
    public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        for request in requests {
            if request.characteristic.properties.contains(.write) {
                // 处理写入请求
                handleWriteRequest(request)
                peripheral.respond(to: request, withResult: .success)
            } else {
                peripheral.respond(to: request, withResult: .attributeNotFound)
            }
        }
    }

    // 获取特征值
    private func getCharacteristicValue(for characteristic: CBCharacteristic) -> Data? {
        // 返回特征的当前值
        return characteristic.value
    }

    // 处理写入请求
    private func handleWriteRequest(_ request: CBATTRequest) {
        // 处理写入数据
        if let data = request.value {
            console.log("写入数据：\(data)")
        }
    }
}
